package cn.kgc.itrip.service.hotelOrderService;

import cn.kgc.itrip.common.*;
import cn.kgc.itrip.dto.Dto;
import cn.kgc.itrip.mapper.hotelOrder.HotelOrderMapper;
import cn.kgc.itrip.mapper.itripHotel.ItripHotelMapper;
import cn.kgc.itrip.mapper.itripHotelOrder.ItripHotelOrderMapper;
import cn.kgc.itrip.mapper.itripHotelRoom.ItripHotelRoomMapper;
import cn.kgc.itrip.mapper.itripOrderLinkUser.ItripOrderLinkUserMapper;
import cn.kgc.itrip.pojo.*;
import cn.kgc.itrip.vo.order.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static java.math.BigDecimal.ROUND_DOWN;

/**
 * @program: love_travel
 * @description: 酒店订单，功能实现
 * @author: Mr.Wang
 * @create: 2020-04-02 15:55
 **/

@Service
public class HotelOrderServiceImpl implements HotelOrderService{

    @Resource
    private ValidationToken validationToken;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private ItripHotelMapper itripHotelMapper;
    @Resource
    private ItripHotelRoomMapper itripHotelRoomMapper;
    @Resource
    private HotelOrderMapper hotelOrderMapper;
    @Resource
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private ItripOrderLinkUserMapper itripOrderLinkUserMapper;


    /**
     * 生成订单前,获取预订信息
     * @param validateRoomStoreVO
     * @param token
     * @param userAgent
     * @return
     */
    @Override
    public Dto addNewOrder(ValidateRoomStoreVO validateRoomStoreVO, String token, String userAgent)throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(validateRoomStoreVO.getHotelId())){
            return DtoUtil.returnFail("hotelId不能为空","100510");
        }
        if (EmptyUtils.isEmpty(validateRoomStoreVO.getRoomId())){
            return DtoUtil.returnFail("roomId不能为空","100511");
        }
        if (validateRoomStoreVO.getCheckInDate()==null ||validateRoomStoreVO.getCheckOutDate()==null){
            return DtoUtil.returnFail("时间不能未空","100514");
        }
        if (validateRoomStoreVO.getCheckInDate().getTime()>validateRoomStoreVO.getCheckOutDate().getTime()){
            return DtoUtil.returnFail("入住时间不能晚于退房时间","100514");
        }
        //准备数据
        //得到酒店
        ItripHotel hotel=itripHotelMapper.getItripHotelById(validateRoomStoreVO.getHotelId());
        //得到房间
        ItripHotelRoom room=itripHotelRoomMapper.getItripHotelRoomById(validateRoomStoreVO.getRoomId());
        //返回的数据
        RoomStoreVO roomStoreVO=new RoomStoreVO();
        //输入值
        roomStoreVO.setCheckInDate(validateRoomStoreVO.getCheckInDate());
        roomStoreVO.setCheckOutDate(validateRoomStoreVO.getCheckOutDate());
        roomStoreVO.setCount(1);
        roomStoreVO.setHotelId(hotel.getId());
        roomStoreVO.setHotelName(hotel.getHotelName());
        roomStoreVO.setRoomId(room.getId());
        //大数据类型
        roomStoreVO.setPrice(BigDecimal.valueOf(room.getRoomPrice()));

        //计算库存
        //查询条件
        Map parm=new HashMap();
        parm.put("startTime",validateRoomStoreVO.getCheckInDate());
        parm.put("endTime",validateRoomStoreVO.getCheckOutDate());
        parm.put("hotelId1",validateRoomStoreVO.getHotelId());
        parm.put("roomId1",validateRoomStoreVO.getRoomId());
        //调用存储库存，填充实时库存表中的记录数
        hotelOrderMapper.fulsh(parm);
        //查询实时库存表，进行库存的运算
        List<ItripHotelTempStore> store =hotelOrderMapper.findTempStore(parm);
        if (EmptyUtils.isEmpty(store)){
            return DtoUtil.returnFail("暂时无房","100512");
        }
        roomStoreVO.setStore(store.get(0).getStore());
        return DtoUtil.returnDataSuccess(roomStoreVO);
    }

    /**
     * 生成订单
     * @param itripAddHotelOrderVO
     * @param token
     * @param userAgent
     * @return
     */
    @Override
    public Dto addHotelOrder(ItripAddHotelOrderVO itripAddHotelOrderVO, String token, String userAgent)throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (itripAddHotelOrderVO.getCheckInDate()==null ||itripAddHotelOrderVO.getCheckOutDate()==null
                ||itripAddHotelOrderVO.getCount()==null||itripAddHotelOrderVO.getCount()==0||
        itripAddHotelOrderVO.getHotelId()==null||itripAddHotelOrderVO.getHotelId()==0||
        itripAddHotelOrderVO.getHotelName()==null||itripAddHotelOrderVO.getLinkUser()==null||
        itripAddHotelOrderVO.getRoomId()==null||itripAddHotelOrderVO.getRoomId()==0){
            return DtoUtil.returnFail("不能提交空，请填写订单信息","100506");
        }
        //库存的校验
        Map parm=new HashMap();
        parm.put("startTime",itripAddHotelOrderVO.getCheckInDate());
        parm.put("endTime",itripAddHotelOrderVO.getCheckOutDate());
        parm.put("hotelId1",itripAddHotelOrderVO.getHotelId());
        parm.put("roomId1",itripAddHotelOrderVO.getRoomId());
        parm.put("count",itripAddHotelOrderVO.getCount());
        boolean i=findCount(parm);
        if (!i){
            return DtoUtil.returnFail("库存不足","100507");
        }
        ItripHotelOrder order=new ItripHotelOrder();
        BeanUtils.copyProperties(itripAddHotelOrderVO,order);
        //用户信息
        ItripUser user=validationToken.getCurrentUser(token);
        order.setUserId(user.getId());
        //创建人
        order.setCreatedBy(user.getId());
        //预定天数
        int days = DateUtil.getBetweenDates(itripAddHotelOrderVO.getCheckInDate(), itripAddHotelOrderVO.getCheckOutDate()).size()-1;
       order.setBookingDays(days);
       //订单状态
        order.setOrderType(0);
        //支付金额
        ItripHotelRoom roomId = itripHotelRoomMapper.getItripHotelRoomById(itripAddHotelOrderVO.getRoomId());
        BigDecimal decimal = BigDecimalUtil.OperationASMD(days * itripAddHotelOrderVO.getCount(), roomId.getRoomPrice(),
                BigDecimalUtil.BigDecimalOprations.multiply, 2, ROUND_DOWN);
        order.setPayAmount(decimal);
        //入住人的姓名
        List<ItripUserLinkUser> linkUser=itripAddHotelOrderVO.getLinkUser();
        if (EmptyUtils.isNotEmpty(linkUser)){
            StringBuffer st=new StringBuffer(",");
            for (int j = 0; j <linkUser.size() ; j++) {
                if (j!=linkUser.size()-1){
                    st.append(linkUser.get(j).getLinkUserName()+",");
                }else {
                    st.append(linkUser.get(j).getLinkUserName());
                }
            }
            order.setLinkUserName(st.toString());
        }

        //预定平台
        if(token.startsWith("token:PC-")){
            order.setBookType(0);
        }else if(token.startsWith("token:MOBILE-")){
            order.setBookType(1);
        }else{
            order.setBookType(2);
        }

        //创建时间
        order.setCreationDate(new Date());

        //订单编号   机器码+时间+md5
        StringBuilder md5 = new StringBuilder("");
        md5.append(itripAddHotelOrderVO.getHotelId());
        md5.append(itripAddHotelOrderVO.getRoomId());
        md5.append(System.currentTimeMillis());
        md5.append(Math.random()*100000000);
        String md5Str = MD5.getMd5(md5.toString(), 6);

        StringBuilder sb1 = new StringBuilder("D1000001");
        sb1.append(DateUtil.format(new Date(),"yyyyMMddHHmmss"));
        sb1.append(md5Str);
        order.setOrderNo(sb1.toString());

         //修改
        int flag1 = 0;
        if(order.getId() != null){
            //删除旧的联系人
            itripOrderLinkUserMapper.deleteItripOrderLinkUserByOrderId(order.getId());
            order.setModifiedBy(user.getId());
            order.setModifyDate(new Date());
            flag1 = itripHotelOrderMapper.updateItripHotelOrder(order);
        }else{//新增
            flag1 = itripHotelOrderMapper.insertItripHotelOrder(order);
        }
        if(flag1>0){
            if(EmptyUtils.isNotEmpty(linkUser)){
                for (ItripUserLinkUser lUser:linkUser){
                    ItripOrderLinkUser orderLinkUser = new ItripOrderLinkUser();
                    BeanUtils.copyProperties(linkUser,orderLinkUser);
                    orderLinkUser.setLinkUserId(lUser.getId());
                    orderLinkUser.setOrderId(order.getId());
                    orderLinkUser.setCreationDate(new Date());
                    orderLinkUser.setCreatedBy(user.getId());
                    itripOrderLinkUserMapper.insertItripOrderLinkUser(orderLinkUser);
                }
            }
        }else{
            return DtoUtil.returnFail("生成订单失败","100505");
        }
        Map result = new HashMap();
        result.put("orderNo",order.getOrderNo());
        result.put("id",order.getId());
        return DtoUtil.returnDataSuccess(result);
    }

    /**
     * 修改房间
     * @param validateRoomStoreVO
     * @param token
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public Dto valiDateRoomStore(ValidateRoomStoreVO validateRoomStoreVO, String token, String userAgent)throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(validateRoomStoreVO.getHotelId())){
            return DtoUtil.returnFail("hotelId不能为空","100515");
        }
        if (EmptyUtils.isEmpty(validateRoomStoreVO.getRoomId())){
            return DtoUtil.returnFail("roomId不能为空","100516");
        }
        if (validateRoomStoreVO.getCheckInDate()==null ||validateRoomStoreVO.getCheckOutDate()==null){
            return DtoUtil.returnFail("时间不能未空","100514");
        }
        if (validateRoomStoreVO.getCheckInDate().getTime()>validateRoomStoreVO.getCheckOutDate().getTime()){
            return DtoUtil.returnFail("入住时间不能晚于退房时间","100514");
        }
        if (validateRoomStoreVO.getCount()==null ||validateRoomStoreVO.getCount()==0){
            return DtoUtil.returnFail("请输入房间数","100518");
        }
        //库存的校验
        Map parm=new HashMap();
        parm.put("startTime",validateRoomStoreVO.getCheckInDate());
        parm.put("endTime",validateRoomStoreVO.getCheckOutDate());
        parm.put("hotelId1",validateRoomStoreVO.getHotelId());
        parm.put("roomId1",validateRoomStoreVO.getRoomId());
        parm.put("count",validateRoomStoreVO.getCount());
        boolean i=findCount(parm);
        if (!i){
            return DtoUtil.returnFail("库存不足","100507");
        }
        return DtoUtil.returnSuccess("修改成功");
    }

    /**
     * 根据订单ID查看个人订单详情
     * @param orderId
     * @param token
     * @param userAgent
     * @return
     */
    @Override
    public Dto findPersonalOrderInfo(String orderId, String token, String userAgent)throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(orderId)){
            return DtoUtil.returnFail("请传递参数：orderId","100525");
        }
        ItripListHotelOrderVO vo =new ItripListHotelOrderVO();
        ItripHotelOrder hotelOrder = itripHotelOrderMapper.getItripHotelOrderById(Long.valueOf(orderId));
        if (EmptyUtils.isNotEmpty(hotelOrder)){
            vo.setId(hotelOrder.getId());
            vo.setHotelId(hotelOrder.getHotelId());
            vo.setHotelName(hotelOrder.getHotelName());
            vo.setOrderNo(hotelOrder.getOrderNo());
            vo.setOrderType(hotelOrder.getOrderType());
            vo.setLinkUserName(hotelOrder.getLinkUserName());
            vo.setCreationDate(hotelOrder.getCreationDate());
            vo.setCheckInDate(hotelOrder.getCheckInDate());
            vo.setPayAmount(hotelOrder.getPayAmount());
            vo.setOrderStatus(hotelOrder.getOrderStatus());
            return DtoUtil.returnDataSuccess(vo);
        }
        return DtoUtil.returnFail("没有相关订单信息","100526");
    }


    /**
     * 根据订单ID查看个人订单详情-房型相关信息
     * @param orderId
     * @param token
     * @param userAgent
     * @return
     */
    @Override
    public Dto findPersonalOrderRoomInfo(String orderId, String token, String userAgent) throws Exception{
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(orderId)){
            return DtoUtil.returnFail("请传递参数：orderId","100529");
        }
        ItripPersonalOrderRoomVO vo=hotelOrderMapper.findOrderRoomVO(orderId);
        if (EmptyUtils.isEmpty(vo)){
            return DtoUtil.returnFail("没有相关订单房型信息","100530");
        }
        return DtoUtil.returnDataSuccess(vo);
    }

    /**
     * 根据个人订单列表，并分页显示
     * @param itripSearchOrderVO
     * @param token
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public Dto findPersonalOrderList(ItripSearchOrderVO itripSearchOrderVO, String token, String userAgent) throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(itripSearchOrderVO.getOrderType())){
            return DtoUtil.returnFail("请传递参数：orderType","100501");
        }
        if (EmptyUtils.isEmpty(itripSearchOrderVO.getOrderStatus())){
            return DtoUtil.returnFail("请传递参数：orderStatus","100502");
        }
        //设置当前页
        //设置当前页，默认从第一页开始
        int pageNo= Constants.DEFAULT_PAGE_NO;
        if (EmptyUtils.isNotEmpty(itripSearchOrderVO.getPageNo())){
            pageNo=itripSearchOrderVO.getPageNo();
        }
        //每页显示的数量
        //设置显示的数量
        int pageSize=Constants.DEFAULT_PAGE_SIZE;
        if (EmptyUtils.isNotEmpty(itripSearchOrderVO.getPageSize())){
            pageSize=itripSearchOrderVO.getPageSize();
        }
        String[] split = token.split("-");
        Long userId = Long.valueOf(split[2].toString());
        List<ItripHotelOrder> listOrder=hotelOrderMapper.findUserId(userId,pageNo,pageSize);
        if (EmptyUtils.isNotEmpty(listOrder)){
            List<ItripSearchOrderVO> vos=new ArrayList<>();
            ItripSearchOrderVO vo=null;
            for (ItripHotelOrder order:listOrder){
                vo=new ItripSearchOrderVO();
                BeanUtils.copyProperties(order,vo);
                vos.add(vo);
            }
            return DtoUtil.returnDataSuccess(vos);
        }
        return DtoUtil.returnFail("获取个人订单列表错误","100503");
    }

    /**
     * 根据订单ID获取订单信息
     * @param orderId
     * @return
     */
    @Override
    public Dto findOrderById(Integer orderId)throws Exception {
        if (EmptyUtils.isEmpty(orderId)){
            return DtoUtil.returnFail("没有查询到相应订单","100533");
        }
        ItripHotelOrder hotelOrder = itripHotelOrderMapper.getItripHotelOrderById(Long.valueOf(orderId));
        if (EmptyUtils.isNotEmpty(hotelOrder)){
            return DtoUtil.returnDataSuccess(hotelOrder);
        }
        return DtoUtil.returnFail("没有查询到相应订单","100533");
    }

    /**
     * 修改订单的支付方式和状态
     * @param itripModifyHotelOrderVO
     * @param token
     * @param userAgent
     * @return
     */
    @Override
    public Dto midOrderStatusAndPayType(ItripModifyHotelOrderVO itripModifyHotelOrderVO,  String token,String userAgent)throws Exception {
        //判断
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (itripModifyHotelOrderVO.getId()==null ||itripModifyHotelOrderVO.getId()==0||
        itripModifyHotelOrderVO.getPayType()==null||itripModifyHotelOrderVO.getPayType()==0){
            return DtoUtil.returnFail("不能提交空，请填写订单信息","100523");
        }
        ItripHotelOrder order=new ItripHotelOrder();
        order.setId(itripModifyHotelOrderVO.getId());
        order.setPayType(itripModifyHotelOrderVO.getPayType());
        Integer i = itripHotelOrderMapper.updateItripHotelOrder(order);
        if (i>0){
            return DtoUtil.returnSuccess();
        }
        return DtoUtil.returnFail("修改订单失败","100522");
    }

    /**
     * 支付成功后查询订单信息
     * @param id
     * @param token
     * @param userAgent
     * @return
     * @throws Exception
     */
    @Override
    public Dto findSuccessOrderInfo(Integer id, String token, String userAgent)throws Exception {
        if (!validationToken.validateToken(token,userAgent)){
            return DtoUtil.returnFail("token失效，请重登录","100000");
        }
        if (EmptyUtils.isEmpty(id)){
            return DtoUtil.returnFail("id不能为空","100519");
        }
        ItripHotelOrder order = itripHotelOrderMapper.getItripHotelOrderById(Long.valueOf(id));
        if (EmptyUtils.isNotEmpty(order)){
            return  DtoUtil.returnDataSuccess(order);
        }
        return DtoUtil.returnFail("获取数据失败","100520");
    }


    public boolean findCount(Map parm) {
        Integer count = (Integer) parm.get("count");
        hotelOrderMapper.fulsh(parm);
        List<ItripHotelTempStore> store = hotelOrderMapper.findTempStore(parm);
        if (EmptyUtils.isNotEmpty(store)){
            if (store.get(0).getStore()>=count){
                return true;
            }
        }
        return false;
    }
}
